package com.szsfm.vehiclemanagement.mvp.presenter;

import android.content.Context;

import com.szsfm.vehiclemanagement.base.BasePresenter;
import com.szsfm.vehiclemanagement.bean.User;
import com.szsfm.vehiclemanagement.manager.GreenDaoManager;
import com.szsfm.vehiclemanagement.mvp.model.IUserLoginModel;
import com.szsfm.vehiclemanagement.mvp.model.modelImpl.UserLoginModelImpl;
import com.szsfm.vehiclemanagement.mvp.view.IUserLoginView;
import com.szsfm.vehiclemanagement.tcp.TcpCore;
import com.szsfm.vehiclemanagement.tcp.TcpUtil;

/**
 * Created by zhoubigbo on 2017/11/29.
 */

public class LoginPresenter extends BasePresenter implements IUserLoginModel.UserLoginListener {


    protected IUserLoginModel loginModel;
    protected IUserLoginView loginView;
    private Context mContext;
    private User mDefaultUser;

    public LoginPresenter(IUserLoginView view) {
        this.loginView = view;
        loginModel = new UserLoginModelImpl();
    }

    public void setContext(Context context) {
        mContext = context;
    }

    public void prepare() {
        mDefaultUser = GreenDaoManager.getInstance().getUserDao().loadByRowId(0);
        if (mDefaultUser != null) {
            if (loginView != null) {
                loginView.showDefaultUser(mDefaultUser.getUsername(), mDefaultUser.getPassword());
            }
            User.shareInstance().setUsername(mDefaultUser.getUsername());
            User.shareInstance().setPassword(mDefaultUser.getPassword());
        }
    }

    public void login(String username, String password) {
        if (loginView != null) {
            loginView.startLogin();
        }
        if (loginModel != null) {
            loginModel.userLogin(username, password, this);
        }
    }

    @Override
    public void loginFailed(String s) {
        loginView.loginError(s);
    }

    @Override
    public void loginSuccess(User user) {
        if (mDefaultUser==null)
        GreenDaoManager.getInstance().getUserDao().insert(user);
        // MainActivity.startSelf(this);
    }
}
